package cn.zhz.springdoc.springboot.config.v2;

import cn.zhz.springdoc.springboot.property.OpenApiProperty;
import cn.zhz.springdoc.springboot.service.impl.OpenApi2ParserImpl;
import cn.zhz.springdoc.springboot.util.PropertyUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2Mapper;

/**
 * @author ZHZ
 * @since 2022-11-16
 */
@ConditionalOnClass({ServiceModelToSwagger2Mapper.class})
@Import({OpenApi2ParserImpl.class})
public class OpenApi2Config {


    @Bean
    @Primary
    public Docket docketCustom(OpenApiProperty openApiProperty) {

        String[] packagesToScan = openApiProperty.getPackagesToScan();
        String[] pathsToMatch = openApiProperty.getPathsToMatch();

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .description(openApiProperty.getGroupName())
                        .termsOfServiceUrl("http://" + PropertyUtil.getHost() + ":" + PropertyUtil.getPort() + PropertyUtil.getContextPath())
                        .version("v1.0.0")
                        .build())
                //分组名称
                .groupName(openApiProperty.getGroupName())
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage(packagesToScan.length > 0 ? packagesToScan[0] : ""))
                .paths(PathSelectors.ant(pathsToMatch.length > 0 ? pathsToMatch[0] : "/**"))
                .build();
    }
}
